<template>
  <div style="padding: 15px">
    <vxe-toolbar
      id="warehouseLocationId"
      :custom="{ storage: true }"
      :refresh="{ query: findList }"
    >
      <template v-slot:tools>
        <div title="导出全部" class="vxe-tools--operate-btn vxe-tools--operate-export-btn" @click="AllDataEventAll">
          <i class="vxe-icon--download"/>
        </div>
      </template>
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :export-config='{type:"csv"}'
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <!--<vxe-table-column type="checkbox" width="60"></vxe-table-column>-->
       <vxe-table-column>
        <vxe-table-column
          field="shipmentName"
          title="入驻商"
          min-width="200"
        />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.shipmentName" clearable filterable placeholder="请选择入驻商">
            <el-option
              v-for="item in options"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="warehouseName"
          title="仓库"
          min-width="200"
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode"
                     @change="selectWarehouse(listQuery.warehouseCode)"
                     placeholder="请选择所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="warehouseSpaceName"
          title="库区"
          min-width="200"
        />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseSpaceCode"
                     @change="selectWarehouseSpace(listQuery.warehouseSpaceCode)"
                     placeholder="请选择所属库区 " style="width:100%" clearable>
            <el-option
              v-for="item in spaceData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="locationName"
          title="库位"
          min-width="200"
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.locationName"
            placeholder="请输入库位"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="goodsName"
          title="商品名称"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.goodsName"
            placeholder="请输入商品名称"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="goodCode"
          title="商品编码"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.goodCode"
            placeholder="请输入商品编码"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="goodsBarCode"
          title="商品条码"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.goodsBarCode"
            placeholder="请输入商品条码"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="containerBarCode"
          title="容器号"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.containerBarCode"
            placeholder="请输入容器号"
            clearable
          />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="expirationQuantity"
          title="保质期天数"
          min-width="180"
          sortable
        />
        <template v-slot:header="{ column }">
          <!-- <el-input v-model="listQuery.expirationQuantity" placeholder="请输入保质期天数" clearable /> -->
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.expirationQuantityFloor"
              placeholder="下限"
              type='number' style="width:45%;"
              ref="expiration"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.expirationQuantityCeiling"
              placeholder="上限"
              type='number' style="width:45%;"
            />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtManufacture"
          title="生产日期"
          min-width="400"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtManufacture"
            type="daterange"
            value-format="yyyy-MM-dd"
            style="width:100%"

            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtManufacture')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtExpire"
          title="过期日期"
          min-width="400"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtExpire"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"

            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtExpire')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtStock"
          title="存货日期"
          min-width="400"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtStock"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"

            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtStock')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="receiveLot"
          title="批次"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.receiveLot"
            placeholder="请输入入库批次"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="goodsStatusName"
          title="库存状态"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.goodsStatusName"
            placeholder="请输入库存状态"
            clearable
          />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="isLock"
          title="锁定状态"
          min-width="150"
          sortable
          :formatter="formatterIsLock"
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.isLock"
            placeholder="请选择锁定状态"
            clearable
          >
            <el-option
              v-for="item in lockList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="unitName"
          title="基本单位"
          min-width="140"
          fixed="right"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.unitName"
            placeholder="请输入单位"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="quantity"
          title="库存数量"
          min-width="180"
          fixed="right"
          sortable
        />
        <template v-slot:header="{ column }">
          <!-- <el-input
            v-model="listQuery.quantity"
            placeholder="请输入库存数量"
            clearable
          /> -->
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.quantityFloor"
              placeholder="下限"
              type='number' style="width:45%;"
              ref="quantity"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.quantityCeiling"
              placeholder="上限"
              type='number' style="width:45%;"
            />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="canUseQuantity"
          title="可用数量"
          min-width="180"
          fixed="right"
          :formatter="formatterCanUseQuantity"
        />
        <template v-slot:header="{ column }">
          <!-- <el-input
            v-model="listQuery.canUseQuantity"
            placeholder="请输入可用库存数量"
            clearable
          /> -->
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.canUseQuantityFloor"
              placeholder="下限"
              ref="canUseQuantity"
              type='number' style="width:45%;"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.canUseQuantityCeiling"
              placeholder="上限"
              type='number' style="width:45%;"
            />
          </el-row>
        </template>
      </vxe-table-column>

      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.tempInventory == 0">
            <template v-if="scope.row.isLock == 0">
              <el-tooltip  effect="dark" content="锁定">
                <vxe-button type="text" @click="funcLock(scope.row.code)">
                  <i class="el-icon-lock" />
                </vxe-button>
              </el-tooltip>
            </template>
            <template v-if="scope.row.isLock == 1">
              <el-tooltip  effect="dark" content="解锁">
                <vxe-button type="text" @click="funcUnlock(scope.row.code)">
                  <i class="el-icon-unlock" />
                </vxe-button>
              </el-tooltip>
            </template>
            <el-tooltip  effect="dark" content="批次调整">
              <vxe-button type="text" @click="funcAdjust(scope.row.code)">
                <i class="el-icon-edit" />
              </vxe-button>
            </el-tooltip>
          </template>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
      @page-change="handlePageChange"
    />

    <vxe-modal
      v-model="modelAdjustFlag"
      title="批次调整"
      width="600"
      height="700"
      destroy-on-close
      resize
    >
      <compAdjust :batchCode="batchCode" @fatherCancel="fatherCancel" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import { inventoryList, inventoryLock, inventoryUnlock, exportinventoryList} from "@/api/store";
import compAdjust from "./components/inventoryAdjust";
import { getWarehouse, getWarehouseSpace, getLocation, exportTask } from '@/api/basicInfo'
import { shipments } from '@/api/outStorage'
import { dataConversionUtil } from './components/excel.js'
export default {
  name: "库存管理",
  components: {
    compAdjust,
  },
  data() {
    return {
      exportAllloading:false, //导出全部弹窗状态
      lockList: [
        //状态
        { code: "0", name: "否" },
        { code: "1", name: "是" },
      ],
      message: "",
      // 日期选项
      pickerOptions: {
        // disabledDate(time) {
        //   return time.getTime() > Date.now();
        // },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      loading: false,
      allAlign: "center",
      tableData: [],
      modelAdjustFlag: false,
      gmtExpire: "", //过期日期 ,
      gmtManufacture: "", //生产日期 ,
      gmtStock: "", //存货日期 ,
      warehouseData: [],           //仓库列表
      spaceData: [],               //库区列表
      locationData: [],
      listQuery: {
        total: 0, //总数
        createdBy: "", //创建人
        modifiedBy: "", //修改人
        code: "", //数据标识 ,
        goodsBarCode: "", //商品条码 ,
        goodsCode: "", //商品 ,
        containerBarCode:'',
        goodsName: "", //商品名称 ,
        goodsUnit: "", //单位 ,
        isLock: "", //锁定状态 ,
        location: "", //库位 ,
        lot: "", //批次号 ,
        quantity: "", //数量 ,
        remarks: "", //备注 ,
        shipmentCode: "", //入驻商 ,
        status: "", //库存状态 ,
        useQuantity: "", //占用数量 ,
        warehouseCode: "", //仓库 ,
        warehouseSpaceCode: "", //库区
        pageNum: 1,
        pageSize: 10,
        sortField: "",
        sortType: "",
        expirationQuantityFloor: "", //保质期
        expirationQuantityCeiling: "",
        quantityFloor: "", //库存数量
        quantityCeiling: "",
        canUseQuantityFloor: "", //可用数量
        canUseQuantityCeiling: "",
        shipmentName:'',  //入驻商
      },
      batchCode:'',
      options: []
    };
  },
  created() {
    this.findList();
  },
  methods: {
    // 选择仓库
    selectWarehouse(val) {
      getWarehouseSpace(val).then(response => {
        this.spaceData = response.data
      });
    },
    // 选择仓库库区
    selectWarehouseSpace(val) {
      getLocation(this.listQuery.warehouseCode, val, "").then(response => {
        this.locationData = response.data
      });
    },
    changeDate(value, prefix) {
      // 处理时间范围 start-end
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    formatterIsLock({ cellValue }) {
      if (cellValue == "0") {
        return "否";
      } else if (cellValue == "1") {
        return "是";
      }
    },
    // 可用数量 = 库存数量 - 占用数量
    formatterCanUseQuantity({ cellValue, row }) {
      return row.quantity - row.useQuantity;
    },

    //  获取列表
    findList() {
      // getLocation(this.listQuery.warehouseCode, this.listQuery.spaceCode, "").then(response => {
      //   this.locationData = response.data
      // });
      shipments().then(res => {
        this.options = res.data
      })
      if (
        // 保质期拦截
        this.listQuery.expirationQuantityCeiling &&
        Number(this.listQuery.expirationQuantityFloor) >
          Number(this.listQuery.expirationQuantityCeiling)
      ) {
        this.$message.error("查询保质期天数下限不得大于上限！");
        this.$refs.expiration.focus();
        return;
      }
      if (
        // 库存数量拦截
        this.listQuery.quantityCeiling &&
        Number(this.listQuery.quantityFloor) >
          Number(this.listQuery.quantityCeiling)
      ) {
        this.$message.error("查询库存数量下限不得大于上限！");
        this.$refs.quantity.focus();
        return;
      }
      if (
        // 可用数量拦截
        this.listQuery.canUseQuantityCeiling &&
        Number(this.listQuery.canUseQuantityFloor) >
          Number(this.listQuery.canUseQuantityCeiling)
      ) {
        this.$message.error("查询可用数量下限不得大于上限！");
        this.$refs.canUseQuantity.focus();
        return;
      }
      // let temp = JSON.parse(JSON.stringify(this.listQuery));
      // delete temp.gmtManufacture;
      // delete temp.gmtExpire;
      // delete temp.gmtStock;

      this.loading = true;
      return new Promise(reslove =>{
       inventoryList(this.listQuery).then((response) => {
        this.tableData = response.data.records;
        this.listQuery.total = response.data.total;
        this.loading = false;
        reslove();
       });
       getWarehouse().then(response => {
        this.warehouseData = response.data
       });
       getWarehouseSpace(this.listQuery.warehouseCode).then(response => {
        this.spaceData = response.data
       });
     })
    },
    // 锁定库存
    funcLock(code) {
      this.$confirm("确认锁定吗？")
        .then((_) => {
          inventoryLock(code).then((response) => {
            if (response.status == 0) {
              this.$message({ message: response.msg, type: "success" });
              this.findList();
            } else {
              this.$message.error(response.msg);
            }
          });
        })
        .catch((_) => {});
    },
    // 解锁库存
    funcUnlock(code) {
      this.$confirm("确认解锁吗？")
        .then((_) => {
          inventoryUnlock(code).then((response) => {
            if (response.status == 0) {
              this.$message({ message: response.msg, type: "success" });
              this.findList();
            } else {
              this.$message.error(response.msg);
            }
          });
        })
        .catch((_) => {});
    },
    // 批次调整
    funcAdjust(code) {
      this.batchCode = code
      this.modelAdjustFlag = true;
    },

    fatherCancel(type) {
      this.modelAdjustFlag = false;
      if (type === "success") {
        this.$message({ message: "操作成功", type: "success" });
      }
      this.findList();
    },
    // 导出全部
    AllDataEventAll () {
      let params = {
        dataType: 'INVENTORY',
        filter: this.listQuery
      }
      exportTask(params).then(data => {
        this.$message.success(data.msg)
      })
      // this.exportAllloading = true
      // exportinventoryList(this.listQuery).then(data => {
      //   let tableHeader = [
      //     ['入驻商','仓库', '库区','库位', '商品名称', '商品编码','商品条码', '容器号', '保质期天数', '生产日期', '过期日期', '存货日期', '批次', '库存状态','锁定状态','基本单位','库存数量','可用数量'],
      //   ]
      //   let dataList = []
      //   data.data.records.forEach(v=>{
      //     dataList.push([v.shipmentName, v.warehouseName,v.warehouseSpaceName,v.locationName,v.goodsName ,v.goodCode ,v.goodsBarCode,v.containerBarCode  ,v.expirationQuantity ,v.gmtManufacture,v.gmtExpire  ,v.gmtStock ,v.receiveLot  ,v.goodsStatusName , v.isLock === 1 ? '是' : '否'   ,v.unitName   ,v.quantity  ,v.canUseQuantity])
      //   })
      //   dataConversionUtil.dataToExcel('数据',tableHeader, dataList);
      // }).finally(()=>{
      //   this.exportAllloading = false
      // })
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "合计";
          }
          if (["pageviews", "forecast"].includes(column.property)) {
            return XEUtils.sum(data, column.property);
          }
          return null;
        }),
      ];
    },
  },
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
